import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Heand from '../../component/heand';
import { useNavigate } from "react-router-dom";
import { Input, Button } from 'antd';

function Add_newdoor_jianjie_image() {

  const [image, setImage] = useState(null);
  const [imageUrl, setImageUrl] = useState('');


  
  

const navigate = useNavigate()
  const handleImageChange = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onloadend = () => {
      setImage(file);
      setImageUrl(reader.result);
    };

    if(file instanceof Blob)
    {
       reader.readAsDataURL(file);
    }
   


  };

 

  const handleSubmit = (event) => {
    event.preventDefault();

    // 上传图片到LeanCloud
    const formData = new FormData();
    formData.append('file', image);
    formData.append('name', image.name);
    axios.post('https://api.leancloud.cn/1.1/files/file', formData, {
      headers: {
        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
        'Content-Type': 'image/jpeg'
      }
    })
      .then(response => {
        console.log(response)
        const imageUrl = response.data.url;

        // 将商品信息添加到LeanCloud
        axios.post('https://api.leancloud.cn/1.1/classes/x_jianjie_image', {
          
          image_url: imageUrl,
          
        }, {
          headers: {

            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
            'Content-Type': 'application/json',
          }
        })
          .then(() => {
            // 添加成功后的处理逻辑
            console.log('商品添加成功');
            
            setImage('')
            setImageUrl('')
            
            // setBcid('')
            navigate('/login')
          })
          .catch(error => {
            // 添加失败后的处理逻辑
            console.error('商品添加失败', error);
          });
      })
      .catch(error => {
        // 图片上传失败后的处理逻辑
        console.error('图片上传失败', error);
      });
  };
//   console.log(isLogined())

 

  
 

  return (

    <div className='pushinput'>
      <Heand />

      <form className='pushtj' >
       
       
        <div>
          <label htmlFor="image">简介背景图片：</label>
          <Input className="xqinp" type="file" id="image" onChange={handleImageChange} />
          {imageUrl && <img className='pushimage' src={imageUrl} alt="商品图片" />}
        </div>
       

        <Button onClick={handleSubmit} >添加简介背景图</Button>
      </form>
    </div>
  )
}

export default Add_newdoor_jianjie_image;